import axios, { type AxiosRequestConfig } from 'axios';
// import qs from 'querystring'
import { SUCCESS_STATUS_ENUM, TOKEN_EXPIRED } from '@/enums/request';
import router from '@/router';
import { message } from 'ant-design-vue';
import { getCookieFun, removeCookieFun } from './storage';

const service = axios.create({
  baseURL: '/api',
  timeout: 10000,
});

// 请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 在此处添加token等请求头处理
    config.headers = {
      ...config.headers,
      'Content-Type': 'application/json',
    };
    if (config.url!.indexOf('user') > -1) {
      config.headers.Authorization = getCookieFun('token') || '';
    }
    // if (config.method === 'post') {
    //   config.data = qs.stringify(config.data)
    // }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 处理响应数据格式
    if (SUCCESS_STATUS_ENUM.includes(response.status)) {
      return response.data;
    }
    return Promise.reject(new Error('请求失败'));
  },
  error => {
    // 统一错误处理
    if (TOKEN_EXPIRED.includes(error.status)) {
      message.error('登录失效！请重新登录');
      logOut();
      return Promise.reject(new Error('登录失效'));
    }
    const errorMessage = error.response?.data?.message || error.message;
    message.error(errorMessage);
    return Promise.reject(new Error(errorMessage));
  }
);

export const logOut = () => {
  removeCookieFun('token');
  router.push('/login');
};

const request = <T>(config: AxiosRequestConfig): Promise<T> => {
  return service(config);
};

export default request;
